package cn.edu.dgut.epidemic;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * mybatis的配置类
 */
@Configuration
@MapperScan(basePackages = "cn.edu.dgut.epidemic.mapper")
public class MyBatisConfig {

    private static Logger logger = Logger.getLogger(MyBatisConfig.class);

    @Bean(name = "dataSource", destroyMethod = "close")
    public BasicDataSource basicDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        //驱动
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        //连接epidemic数据库
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/epidemic");
        //连接数据库的用户
        dataSource.setUsername("root");
        //连接数据库的密码
        dataSource.setPassword("123456");

        dataSource.setInitialSize(3);
        dataSource.setMaxTotal(50);
        dataSource.setMaxIdle(1);
        dataSource.setMaxWaitMillis(4000);
        dataSource.setDefaultAutoCommit(false);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();

        //设置要使用的数据源
        factoryBean.setDataSource(dataSource);

        SqlSessionFactory sqlSessionFactory = null;

        //设置xml文件中的类所在的包
        factoryBean.setTypeAliasesPackage("cn.edu.dgut.epidemic.beans");

        //为了让Mybatis自动将下划线分隔的列名转换为驼峰表示法的属性名
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        factoryBean.setConfiguration(configuration);

        try {
            //设置映射的xml文件的路径
            Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath:cn/edu/dgut/epidemic/mapper*Mapper.xml");
            factoryBean.setMapperLocations(resources);
            //返回的是SqlSessionFactory对象的引用
            sqlSessionFactory = factoryBean.getObject();
        } catch (Exception e) {
            logger.error("解析映射xml文件时异常：" + e.getMessage());
        }

        return sqlSessionFactory;
    }
}
